using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using System.Text;
using System.Text.Json;
using MVCWeekOne.Models;

namespace MVCWeekOne.Controllers
{
    public class DefectiveItemDistributionController : Controller
    {
        private readonly IHttpClientFactory _httpClientFactory;
        private readonly ApiSettings _apiSettings;

        public DefectiveItemDistributionController(IHttpClientFactory httpClientFactory, IOptions<ApiSettings> apiSettings)
        {
            _httpClientFactory = httpClientFactory;
            _apiSettings = apiSettings.Value;
        }

        /// <summary>
        /// 不良品项分布页面
        /// </summary>
        [HttpGet]
        public IActionResult Index()
        {
            var token = HttpContext.Session.GetString("Token");
            if (string.IsNullOrEmpty(token))
            {
                return RedirectToAction("Login", "Account");
            }

            return View();
        }

        /// <summary>
        /// 测试页面
        /// </summary>
        [HttpGet]
        public IActionResult Test()
        {
            return View();
        }

        /// <summary>
        /// 调试页面
        /// </summary>
        [HttpGet]
        public IActionResult Debug()
        {
            return View();
        }

        /// <summary>
        /// 检查数据库数据
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> CheckData()
        {
            try
            {
                var client = _httpClientFactory.CreateClient();
                var token = HttpContext.Session.GetString("Token");
                if (!string.IsNullOrEmpty(token))
                {
                    client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");
                }

                var url = $"{_apiSettings.ReadApiUrl}/DefectiveItemDistribution/GetDefectiveItemDistribution?index=1&size=10";
                var response = await client.GetAsync(url);
                
                if (response.IsSuccessStatusCode)
                {
                    var result = await response.Content.ReadAsStringAsync();
                    return Content(result, "application/json");
                }
                else
                {
                    return Content($"API调用失败: {response.StatusCode}", "text/plain");
                }
            }
            catch (Exception ex)
            {
                return Content($"异常: {ex.Message}", "text/plain");
            }
        }

        /// <summary>
        /// 获取不良品项分布分页数据
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetDefectiveItemDistributionPage(
            int page = 1, 
            int limit = 30, 
            DateTime? startTime = null, 
            DateTime? endTime = null,
            string defectiveItemCode = "",
            string defectiveItemName = "",
            bool export = false)
        {
            var token = HttpContext.Session.GetString("Token");
            if (string.IsNullOrEmpty(token))
            {
                return Json(new { code = 1, msg = "未登录", count = 0, data = new List<DefectiveItemDistributionModel>() });
            }

            try
            {
                var client = _httpClientFactory.CreateClient();
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");

                // 构建查询参数
                var queryParams = new List<string>();
                queryParams.Add($"index={page}");
                queryParams.Add($"size={limit}");
                
                if (startTime.HasValue)
                    queryParams.Add($"startTime={startTime.Value:yyyy-MM-dd HH:mm:ss}");
                
                if (endTime.HasValue)
                    queryParams.Add($"endTime={endTime.Value:yyyy-MM-dd HH:mm:ss}");
                
                if (!string.IsNullOrEmpty(defectiveItemCode))
                    queryParams.Add($"defectiveItemCode={Uri.EscapeDataString(defectiveItemCode)}");
                
                if (!string.IsNullOrEmpty(defectiveItemName))
                    queryParams.Add($"defectiveItemName={Uri.EscapeDataString(defectiveItemName)}");

                var queryString = string.Join("&", queryParams);
                var url = $"{_apiSettings.ReadApiUrl}/DefectiveItemDistribution/GetDefectiveItemDistribution?{queryString}";

                System.Diagnostics.Debug.WriteLine($"调用不良品项分布API: {url}");

                var response = await client.GetAsync(url);
                
                if (response.IsSuccessStatusCode)
                {
                    var result = await response.Content.ReadAsStringAsync();
                    System.Diagnostics.Debug.WriteLine($"不良品项分布API返回: {result}");
                    
                    var distributionResult = JsonSerializer.Deserialize<ApiPageing<DefectiveItemDistributionModel>>(result, new JsonSerializerOptions
                    {
                        PropertyNameCaseInsensitive = true
                    });
                    
                    System.Diagnostics.Debug.WriteLine($"反序列化结果: {JsonSerializer.Serialize(distributionResult)}");
                    
                    if (distributionResult != null)
                    {
                        // 如果是导出，返回文件
                        if (export)
                        {
                            var dataList = distributionResult.PageData?.ToList() ?? new List<DefectiveItemDistributionModel>();
                            return await ExportToExcel(dataList);
                        }

                        return Json(new { 
                            code = 0, 
                            msg = "success", 
                            count = distributionResult.TotaCount,
                            data = distributionResult.PageData?.ToList() ?? new List<DefectiveItemDistributionModel>()
                        });
                    }
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine($"不良品项分布API调用失败: {response.StatusCode}");
                }

                return Json(new { code = 1, msg = "获取不良品项分布数据失败", count = 0, data = new List<DefectiveItemDistributionModel>() });
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"不良品项分布API异常: {ex.Message}");
                return Json(new { code = 1, msg = $"获取不良品项分布数据异常: {ex.Message}", count = 0, data = new List<DefectiveItemDistributionModel>() });
            }
        }

        /// <summary>
        /// 导出不良品项分布数据到Excel
        /// </summary>
        private Task<IActionResult> ExportToExcel(List<DefectiveItemDistributionModel> distributions)
        {
            try
            {
                // 创建CSV格式的数据
                var csvContent = new StringBuilder();
                
                // 添加表头
                csvContent.AppendLine("时间,不良品项编号,不良品项名称,数量,总数量,占比(%)");
                
                // 添加数据行
                foreach (var distribution in distributions)
                {
                    var time = distribution.Time.ToString("yyyy-MM-dd");
                    var percentage = distribution.Percentage.ToString("F2");
                    
                    csvContent.AppendLine($"{time},{distribution.DefectiveItemCode},{distribution.DefectiveItemName},{distribution.Quantity},{distribution.TotalQuantity},{percentage}");
                }
                
                var fileName = $"不良品项分布_{DateTime.Now:yyyyMMdd_HHmmss}.csv";
                var bytes = Encoding.UTF8.GetBytes(csvContent.ToString());
                
                return Task.FromResult<IActionResult>(File(bytes, "text/csv", fileName));
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"导出Excel异常: {ex.Message}");
                return Task.FromResult<IActionResult>(Json(new { code = 1, msg = $"导出失败: {ex.Message}" }));
            }
        }
    }
}
